<template>
  <!-- 教师课程管理 -->
  <div class="container-fluid p-4">
    <el-card class="box-card mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="课程名称">
          <el-input placeholder="请输入我的课程名称" v-model="searchForm.name">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            placeholder="课程分类"
            style="width: 120px; margin-right: 10px"
            v-model="searchForm.category"
          >
            <el-option label="全部课程" value="all"></el-option>
            <el-option label="基础护理" value="basic"></el-option>
            <el-option label="专科护理" value="specialty"></el-option>
            <el-option label="急救技能" value="emergency"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            placeholder="课程难度"
            style="width: 120px; margin-right: 10px"
            v-model="searchForm.difficulty"
          >
            <el-option label="全部" value="all"></el-option>
            <el-option label="入门级" :value="0"></el-option>
            <el-option label="基础级" :value="1"></el-option>
            <el-option label="进阶级" :value="2"></el-option>
            <el-option label="专家级" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <!-- <el-button type="primary" @click="onSearch">查询</el-button> -->
          <el-button @click="onReset">重置</el-button>
          <el-button
            type="success"
            :icon="Plus"
            @click="modalController.openPopup('addCourseModal')"
            >创建课程
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div
              class="card-header d-flex justify-content-between align-items-center"
            >
              <h5 class="mb-0">我的课程</h5>
              <div>
                <el-button-group>
                  <el-button :icon="Grid" />
                  <el-button :icon="List" />
                </el-button-group>
              </div>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col
              v-for="course in filteredCourses"
              :key="course.course.id"
              :span="8"
              class="mb-4"
              @click="toDetail(course.course.id)"
            >
              <el-card class="course-card" shadow="hover">
                <el-image
                  :src="course.course.coverUrl"
                  class="course-image"
                  fit="cover"
                >
                  <template #error>
                    <div
                      class="image-slot"
                      @click="editCourse(course.course.id)"
                    >
                      <el-icon>
                        <Camera />
                      </el-icon>
                      <p>图片加载失败，点击重新上传</p>
                    </div>
                  </template>
                </el-image>
                <div class="course-content">
                  <div
                    class="d-flex justify-content-between align-items-center mb-2"
                  >
                    <el-tag :type="course.course.categoryName"
                      >{{ course.course.categoryName }}
                    </el-tag>
                    <el-rate
                      :model-value="course.course.star"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}分"
                    ></el-rate>
                  </div>
                  <h5 class="course-title">{{ course.course.title }}</h5>
                  <p class="course-description">
                    {{ course.course.description }}
                  </p>
                  <div
                    class="d-flex justify-content-between align-items-center text-muted"
                  >
                    <small>
                      <i class="bi bi-people"></i>
                      {{ course.selectNumber }}人学习
                    </small>
                    <small>
                      <i class="bi bi-clock"></i>
                      {{ course.course.lastingTime }}小时课程
                    </small>
                  </div>
                </div>
                <div class="course-actions">
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Edit"
                    @click.stop="editCourse(course.course.id)"
                    >编辑
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click.stop="deleteCourse(course.course)"
                    >删除
                  </el-button>
                  <el-button @click.stop="openResourceModal(course.course.id)"
                    >管理资源
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <edit-course-modal
    v-model="modalController.popups.editCourseModal"
  ></edit-course-modal>
  <add-course-modal v-model="modalController.popups.addCourseModal" />
  <CourseResourceModal ref="resourceModalRef" :course-id="currentCourseId" />
</template>

<script setup>
import { ref, computed, onMounted, reactive, nextTick, watch } from "vue";
import CourseResourceModal from "@/components/alert/teacher/CourseResourceModal.vue";
import {
  Search,
  Plus,
  Edit,
  Delete,
  Grid,
  List,
  Camera,
} from "@element-plus/icons-vue";
import EditCourseModal from "@/components/alert/teacher/EditCourseModal.vue";
import { modalControllers } from "@/stores/modalController.js";
import AddCourseModal from "@/components/alert/admin/AddCourseModal.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user.js";
import { useRouter } from "vue-router";

const modalController = modalControllers();
const userStore = useUserStore();
const resourceModalRef = ref(null);
const currentCourseId = ref(null);
userStore.selectTeacherCourse(userStore.user.id);
const openResourceModal = (courseId) => {
  currentCourseId.value = courseId;
  console.log("courseId:", courseId);
  // 使用 nextTick 确保 props 更新后再打开弹窗
  nextTick(() => {
    resourceModalRef.value.open();
  });
};
const categories = [
  { label: "全部课程", value: "all" },
  { label: "基础护理", value: "basic" },
  { label: "专科护理", value: "specialty" },
  { label: "急救技能", value: "emergency" },
  { label: "护理管理", value: "management" },
];
watch(
  () => modalController.popups.addCourseModal,
  (newValue, oldValue) => {
    // 当弹窗从“打开”变为“关闭”时
    if (oldValue === true && newValue === false) {
      // 主动重新获取一次当前教师的课程列表
      userStore.selectTeacherCourse(userStore.user.id);
    }
  },
);
const router = useRouter();
const levels = [
  { label: "全部级别", value: "all" },
  { label: "入门级", value: "0" },
  { label: "基础级", value: "1" },
  { label: "进阶级", value: "2" },
  { label: "专家级", value: "3" },
];
const courses = computed(() => {
  return userStore.teacher_myCourse;
});
const editCourse = async (id) => {
  await userStore.changeEditedCourse(id);
  modalController.openPopup("editCourseModal");
};
const searchForm = reactive({
  name: "",
  category: "all",
  difficulty: "all",
});

const onSearch = () => {
  // 触发 computed 属性重新计算，无需额外操作
  console.log("搜索条件:", searchForm);
};

const onReset = () => {
  searchForm.name = "";
  searchForm.category = "all";
  searchForm.difficulty = "all";
  console.log("重置搜索条件:", searchForm);
};
const deleteCourse = (course) => {
  ElMessageBox.confirm(`确定要删除课程 "${course.title}" 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      courses.value = courses.value.filter((c) => c.course.id !== course.id);
      userStore.deleteCourse(course.id);
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const filteredCourses = computed(() => {
  return courses.value.filter((item) => {
    const nameMatch =
      !searchForm.name || item.course.title.includes(searchForm.name);

    const categoryMatch =
      searchForm.category === "all" ||
      categories.find((c) => c.value === searchForm.category)?.label ===
        item.course.categoryName;

    const difficultyMatch =
      searchForm.difficulty === "all" ||
      item.course.difficulty === searchForm.difficulty;

    return nameMatch && categoryMatch && difficultyMatch;
  });
});
const getCategoryType = (category) => {
  switch (category) {
    case "基础护理":
      return "success";
    case "专科护理":
      return "danger";
    case "急救技能":
      return "warning";
    case "护理管理":
      return "info";
    default:
      return "";
  }
};
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const getLevelTagType = (level) => {
  switch (level) {
    case "入门级":
      return "";
    case "基础级":
      return "success";
    case "进阶级":
      return "warning";
    case "专家级":
      return "danger";
    default:
      return "";
  }
};
const toDetail = (id) => {
  router.push(`/course/${id}`);
};
</script>

<style scoped>
/* 确保 Bootstrap Icons 正常显示 */
@import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css");

.course-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.course-image {
  width: 100%;
  height: 480px;
  object-fit: cover;
  margin-bottom: 15px;
}

.course-content {
  flex-grow: 1;
  padding: 0 15px;
}

.course-title {
  font-size: 1.25rem;
  font-weight: bold;
  margin-bottom: 10px;
}

.course-description {
  font-size: 0.9rem;
  color: #606266;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  /* 限制在3行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-actions {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
  cursor: pointer;
}

.image-slot .el-icon {
  font-size: 30px;
  margin-bottom: 5px;
}

[class^="bi-"]::before,
[class*=" bi-"]::before {
  display: inline-block;
  font-family: bootstrap-icons !important;
  font-style: normal;
  font-weight: normal !important;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  vertical-align: -0.125em;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
